import React, { useCallback, useEffect, useState } from "react";
import "@/assets/css/main.scss";
import { useNavigate, useSearchParams } from "react-router-dom";
import {
    login,
} from "@/utils/dataUtil";
import {
    setAuthorization,
    setUserLogin,
    getUserLogin
} from "@/utils/storageUtil";
import ExitContent from "@/components/ExitContent";
import eventBus from "@/utils/eventBus";
import HeadBack from "@/components/HeadBack";
import NormalMain from "@/components/main/NormalMain";
import HospitalMain from "@/components/main/HospitalMain";

export default function Main() {
    const navigate = useNavigate();

    const [searchParams] = useSearchParams();
    
    //员工编号
    const [employeeId, setEmployeeId] = useState();

    //是否不存在该用户 1 是有 0是没有
    const [notUser, setNotUser] = useState(-1);

    useEffect(() => {
        const getHomeMethod = async () => {
            const miId = searchParams.get("mi_id");
            if (miId === undefined || miId === null || miId === "") {
                setNotUser(0);
                return;
            }
            
            //如果用户已经登录过则不进行接口请求
            const userLogin = getUserLogin();
            if(userLogin !== null) {
                const {category = 1} = userLogin;
                setNotUser(category);
                setEmployeeId(userLogin.employeeId);
                return;
            }

            let response = await login({ miId: miId });
            if (response.status === 5000) {
                setNotUser(0);
                return;
            } else {
                const {category = 1} = response.data;
                setAuthorization(response.data.authorization);
                //存储用户信息
                setUserLogin(response.data);
                //员工编号
                setEmployeeId(response.data.employeeId);
                setNotUser(category);
                
            }
        };
        getHomeMethod();
    }, []);

    useEffect(() => {
        eventBus.$emit("axiosInterceptorsFun", navigate);
    }, []); //eslint-disable-line react-hooks/exhaustive-deps


    const refresh = useCallback(() => {
        setNotUser(0);
    }, []);

    return (
        <>
            <HeadBack
                background={"transparent"}
                backTit={""}
                isHome="home"
            ></HeadBack>

            {notUser === 0 && <ExitContent></ExitContent>}

            {notUser === 1 && <NormalMain employeeId={employeeId} refresh={refresh}></NormalMain>}

            {notUser === 2 && <HospitalMain employeeId={employeeId} refresh={refresh}></HospitalMain>}
        </>
    );
}
